#/usr/bin/perl 

use strict;
use LWP::Simple;

my $compile = shift(@ARGV) =~ /-.*s/ ? 0 : 1;

my $org = 'A Beamer Quickstart was written by Rouben Rostamin and can be found at http://www.math.umbc.edu/~rouben/beamer.  It was downloaded locally by Vincenzo Carrino';


my $imgBase = 'http://www.math.umbc.edu/~rouben/beamer';
my $base = 'http://www.math.umbc.edu/~rouben/beamer/quickstart-Z-H-';
my $i = 1;
my $end = '.html';

mkdir 'Beamer Ref' or warn 'Can not make directory';
chdir 'Beamer Ref' or die 'Can not change directory';

my $contents = get('http://www.math.umbc.edu/~rouben/beamer/quickstart.html');
my $css = get('http://www.math.umbc.edu/~rouben/beamer/Local.css');
print "Downloading: Intro, Info\n";
{open my $F, '>', 'contents.html';
    $contents =~ s/href="/href="Files\//g;
    print $F $contents; close $F;
}

{open my $F, '>', 'org.txt'; print $F $org; close $F;}

mkdir 'Files' or warn 'Can not make directory';
chdir 'Files' or die 'Can not change directory';

{open my $F, '>', 'Local.css'; print $F $css; close $F;}

my $ALL;
if($compile){
    open $ALL , '>', 'compiled.html';
    $contents =~ s/href=".+?(\d+).+?"/href="#$1"/g;
    print $ALL $contents;
}
my @images;
while(my $data = get("$base$i$end")){
    print "Downloading Page: $i\n";
    open my $F, '>', "quickstart-Z-H-$i.html";
    print $F $data;
	my @pageImages = $data =~ /src="(.+?)"/gc;
	foreach(@pageImages){push @images, $_;}
    if($compile){
        $data =~ s/href=".+?(\d+).+?"/href="#$1"/g;
        $data =~ s/<body>/<body>\n<a name="$i"><\/a>/;
        print $ALL $data;
    }
    close $F;
    $i++;
}

foreach my $img (@images) {
	print "$img\n";
	my $data = get("$imgBase/$img");
	if ($img =~ /\//) {
		my $tImg = $img;
		$img =~ s/(.+?)\/(.+?)/$2/;
		my ($one,$two) = ($1,$2);
		mkdir "$1";
		chdir "$1" or die 'Can not change directory';
		if ($tImg =~ /-thumb/){
            $tImg =~ s/-thumb//;
			print "$tImg\n";
            my $bigImg = get("$imgBase/$tImg");
            $tImg =~ /themes\/(.+?)$/;
			open my $F, '>', "$1";
			print $F $bigImg;
			close $F;
		}
		$img =~ s/(.+?)\/(.+?)/$2/;
		open my $F, '>', "$img";
		print $F $data;
		close $F;
		chdir ".." or die 'Can not change directory';
	}
	else {
		open my $F, '>', "$img";
		print $F $data;
		close $F;
	}
}
close $ALL if $compile;
